import sqlite3

container_dock = -101
container_desktop = -100
table_name_favorites = 'favorites'
table_name_double_favorites = 'doubleFavorites'
table_name_ease_favorites = 'easeFavorites'

apps_in_dock = []
apps_in_desktop = []
widgets_info_in_desktop = []
folders_info_in_desktop = []

start_marker_str = "component="
end_marker_str = ";end"

#  0-10: _id, title, intent, container, screen, cellX, cellY, spanX, spanY, itemType, appWidgetId,
# 11-18: icon, appWidgetProvider, modified, restored, profileId, rank, options, appWidgetSource
table_keys = [
    '_id', 'title', 'intent', 'container', 'screen', 'cellX', 'cellY', 'spanX', 'spanY', 'itemType', 'appWidgetId',
    'icon', 'appWidgetProvider', 'modified', 'restored', 'profileId', 'rank', 'options', 'appWidgetSource'
]


def table_exists(cursor, table_name):
    cursor.execute("""
        SELECT COUNT(*) 
        FROM sqlite_master 
        WHERE type='table' AND name=?
    """, (table_name,))
    return cursor.fetchone()[0] == 1


def list_tables(cursor):
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
    all_tables = cursor.fetchall()
    return [table[0] for table in all_tables]


def fetch_data_by_container(cursor, table_name, container_value):
    query = f"SELECT * FROM {table_name} WHERE container = ?"
    cursor.execute(query, (container_value,))
    return cursor.fetchall()


# widget
def fetch_data_by_appWidgetId(cursor, table_name):
    query = f"SELECT * FROM {table_name} WHERE appWidgetId > ?"
    cursor.execute(query, (0,))
    return cursor.fetchall()


# 文件夹
def fetch_data_by_itemType(cursor, table_name):
    query = f"SELECT * FROM {table_name} WHERE itemType = ?"
    cursor.execute(query, (2,))
    return cursor.fetchall()


def get_column_names(cursor, table_name):
    """Get column names for a specific table."""
    cursor.execute(f"PRAGMA table_info({table_name})")
    return [column[1] for column in cursor.fetchall()]


def get_component_name(text):
    component_start = "component="
    intent_info = text.split(';')
    for info in intent_info:
        if info.startswith(component_start):
            return info[len(component_start):]
    return ""


# 连接到SQLite数据库（如果文件不存在，则会创建一个新的数据库）
# data/user_de/0/com.zte.mifavor.launcher/databases/launcher.db
conn = sqlite3.connect('launcher.db')
cur = conn.cursor()

try:
    # 创建一个游标对象
    # cur = conn.cursor()
    # 列出数据库中的所有表
    print("Tables in the database:")
    tables = list_tables(cur)
    if tables:
        for table in tables:
            print(table)
    else:
        print("No tables found.")

    # 检查并读取 'favorites' 表
    if table_exists(cur, table_name_favorites):
        cur.execute("SELECT * FROM favorites")

        columns = get_column_names(cur, table_name_favorites)
        if columns:
            print(f"Columns: {', '.join(columns)}")
            print(table_keys)
        else:
            print("No columns found.")

        # 桌面folder
        results = fetch_data_by_itemType(cur, table_name_favorites)
        if results:
            # print(f"\nContent in '{table_name_favorites}' where 'itemType' = 2:")
            print("\nFolder info:")
            for content in results:
                # print(content[1])  # 打印每条记录的content值
                folder_info = [content[0], content[1], content[4], content[5], content[6], content[7], content[8]]
                folders_info_in_desktop.append(folder_info)
        else:
            print(f"No data found in '{table_name_favorites}' where 'container' is {container_dock}.")
        print(folders_info_in_desktop)
        # 桌面folder

        # 桌面folder应用
        for folder_info in folders_info_in_desktop:
            apps_in_folder_info = []
            folder_id = folder_info[0]
            print(f"\nfolder_id: {folder_id}")
            results = fetch_data_by_container(cur, table_name_favorites, folder_id)
            if results:
                # print(f"Content in '{table_name_favorites}' where 'container' = {folder_id}:")
                for content in results:
                    # print(content[1])  # 打印每条记录的content值
                    app_in_folder_info = [content[0], content[1], content[4], content[5], content[6], content[7],
                                          content[8]]
                    apps_in_folder_info.append(app_in_folder_info)
            else:
                print(f"No data found in '{table_name_favorites}' where 'container' is {container_dock}.")
            print(apps_in_folder_info)
        # 桌面folder应用

        # 桌面widget
        results = fetch_data_by_appWidgetId(cur, table_name_favorites)
        if results:
            # print(f"\nContent in '{table_name_favorites}' where 'appWidgetId' > 0:")
            print("\nWidget info:")
            for content in results:
                # print(content[12])  # 打印每条记录的content值
                widget_info = [content[4], content[5], content[6], content[7], content[8], content[12]]
                widgets_info_in_desktop.append(widget_info)
        else:
            print(f"No data found in '{table_name_favorites}' where 'container' is {container_dock}.")
        print(widgets_info_in_desktop)
        # 桌面widget

        # 桌面非文件夹应用
        results = fetch_data_by_container(cur, table_name_favorites, container_desktop)
        if results:
            # print(f"\nContent in '{table_name_favorites}' where 'container' is {container_desktop}:")
            print("\nDesktop App info:")
            for content in results:
                if content[9] == 0:
                    result = get_component_name(content[2])
                    if "/." in result:
                        package_name = result.split('/.')[0]
                        class_name = result.split('/.')[0] + "." + result.split('/.')[1]
                        # print(content[1] + ":" + package_name + "," + class_name)
                        app_info = [content[1], package_name, class_name]
                        apps_in_desktop.append(app_info)
                    elif "/" in result:
                        package_name = result.split('/')[0]
                        class_name = result.split('/')[1]
                        # print(content[1] + ":" + package_name + "," + class_name)
                        app_info = [content[1], package_name, class_name]
                        apps_in_desktop.append(app_info)
        else:
            print(f"No data found in '{table_name_favorites}' where 'container' is {container_desktop}.")
        print(apps_in_desktop)
        # 桌面非文件夹应用

        # dock区应用
        results = fetch_data_by_container(cur, table_name_favorites, container_dock)
        if results:
            # print(f"\nContent in '{table_name_favorites}' where 'container' is {container_dock}:")
            print("\nDock App info:")
            for content in results:
                # print(content[17])  # 打印每条记录的content值
                app_info = [content[1], content[4]]
                apps_in_dock.append(app_info)
        else:
            print(f"No data found in '{table_name_favorites}' where 'container' is {container_dock}.")
        print(apps_in_dock)
        # dock区应用

    else:
        print("The 'favorites' table does not exist.")

    # 检查并读取 'doubleFavorites' 表
    # if table_exists(cur, 'doubleFavorites'):
    #     cur.execute("SELECT * FROM doubleFavorites")
    #     rows_orders = cur.fetchall()
    #
    #     print("\ndoubleFavorites table:")
    #     for row in rows_orders:
    #         print(row)
    # else:
    #     print("The 'doubleFavorites' table does not exist.")

    # 检查并读取 'easeFavorites' 表
    # if table_exists(cur, 'easeFavorites'):
    #     cur.execute("SELECT * FROM easeFavorites")
    #     rows_orders = cur.fetchall()
    #
    #     print("\neaseFavorites table:")
    #     for row in rows_orders:
    #         print(row)
    # else:
    #     print("The 'easeFavorites' table does not exist.")

finally:
    # 关闭游标和连接
    cur.close()
    conn.close()
